package com.neusoft.thread3volatile;
/**
 * volatile是第二种Java多线程同步的机制，根据JLS(Java LanguageSpecifications)的说法，一个变量可以被
 * volatile修饰，在这种情况下内存模型(主内存和线程工作内存)确保所有线程可以看到一致的变量值
 * @author Zhang.Yan
 *
 */
public class VolatileTest 
{

	public static void main(String[] args) 
	{
		for(int i=0;i<10;i++)
		{
	        new Thread() {  
	            public void run() { 
//	            	ThreadTest.one();
	            	ThreadTest.oneSync();
	            };  
	        }.start();
	        new Thread() {  
	            public void run() { 
//	            	ThreadTest.two();
	            	ThreadTest.twoSync();
	            };  
	        }.start();
		}
	}
}

class ThreadTest
{
	static int i = 0, j = 0;
	
	
	static void one() 
	{
		i++;
		try 
        {
			Thread.sleep(5);
		} 
        catch (InterruptedException e)
        {
			e.printStackTrace();
		}
		j++;
	}
	static void two() 
	{
		if(i!=j)
		{
			System.err.println("i=" + i + " j=" + j);
		}
		else
		{
			System.out.println("i=" + i + " j=" + j);
		}
		try 
        {
			Thread.sleep(10);
		} 
        catch (InterruptedException e)
        {
			e.printStackTrace();
		}
	}
	
	static synchronized void oneSync() 
	{
		i++;
		try 
        {
			Thread.sleep(5);
		} 
        catch (InterruptedException e)
        {
			e.printStackTrace();
		}
		j++;
	}
	static synchronized void twoSync() 
	{
		if(i!=j)
		{
			System.err.println("i=" + i + " j=" + j);
		}
		else
		{
			System.out.println("i=" + i + " j=" + j);
		}
		try 
        {
			Thread.sleep(10);
		} 
        catch (InterruptedException e)
        {
			e.printStackTrace();
		}
	}
	
	
	static volatile int vi = 0, vj = 0;
	
	static  void oneVolatile() 
	{
		vi++;
		vj++;
		try 
        {
			Thread.sleep(3);
		} 
        catch (InterruptedException e)
        {
			e.printStackTrace();
		}
	}
	static  void twoVolatile() 
	{
		if(vi!=vj)
		{
			System.err.println("vi=" + vi + " vj=" + vj);
		}
		else
		{
			System.out.println("vi=" + vi + " vj=" + vj);
		}
		try 
        {
			Thread.sleep(3);
		} 
        catch (InterruptedException e)
        {
			e.printStackTrace();
		}
	}
}

